// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import {gameUtils, sdkUtils} from "./utils";

const {ccclass, property} = cc._decorator;
import GameScene from "./GameScene";
import {wxUtils} from "./wx/wxUtils";

@ccclass
export default class BeginScene extends cc.Component {

  @property(cc.Node)
  private btnQRCode: cc.Node = null;

  @property(cc.Sprite)
  private adSprite: cc.Sprite = null;

  @property(cc.Node)
  private gameNode: cc.Node = null;
  private game: GameScene = null;

  @property(cc.Node)
  private bg: cc.Node = null;
  @property(cc.Node)
  private bootstrapNode: cc.Node = null;

  async onLoad() {
    this.game = this.gameNode.getComponent(GameScene);
    this.initAdSprite();
    this.btnQRCode.on('click', this.showAd, this);
    this.bg.on(cc.Node.EventType.TOUCH_START, (e) => {

    });
    if (gameUtils.isRestart) {
      this.onStartTouch();
    }
  }

  onStartTouch() {
    this.node.active = false;
    this.game.startGame();
    const needBootstrap = wxUtils.getBootstrapSync() != "1";
    if (needBootstrap) {
      wxUtils.setBootstrap();
      this.bootstrapNode.active = true;
    } else {
      setTimeout(() => {
        this.game.jump();
      }, 200)
    }

    gameUtils.isRestart = false;
  }

  phbTouch() {
    wxUtils.postMessage({
      message: 'rank'
    })
    cc.director.loadScene("testScene");
  }

  shareTouch() {
    sdkUtils.onShare();
  }

  private async initAdSprite() {
    sdkUtils.getAdCanvas((adCanvas) => {
      this.refreshTexture(adCanvas);
    }, () => {
      this.adSprite.node.active = false;
    });
  }

  refreshTexture(canvas) {
    const texture = new cc.Texture2D();
    texture.initWithElement(canvas);
    texture.handleLoadedTexture();
    const size = cc.view.getVisibleSize();
    this.adSprite.node.width = size.width;
    this.adSprite.node.height = size.height;
    this.adSprite.spriteFrame = new cc.SpriteFrame(texture);
    this.adSprite.node.active = true;
  }

  showAd() {
    sdkUtils.showAD();
  }
}
